<?                                         
define ("RECURSE_TYPE_DAILY", "0");                                         
define ("RECURSE_TYPE_WEEKLY", "1");                                         
define ("RECURSE_TYPE_MONTHLY_DATE", "2");                                         
define ("RECURSE_TYPE_MONTHLY_DAY", "3");                                         
define ("RECURSE_TYPE_YEARLY", "4");                                         
define ("RECURSE_TYPE_WEEKDAY", "5");                                         
define ("RECURSE_TYPE_CUSTOM", "7");            
define ("GLOBAL_CONFIG", "eb-config.txt");                                          

if (isset($HTTP_RAW_POST_DATA)) {                                                                                                                                  
    $input = $HTTP_RAW_POST_DATA;                                                                                                                                  
} else if (strlen($HTTP_POST_VARS["input"])>0) {                                                                                                                                  
    $input = stripslashes($HTTP_POST_VARS["input"]);                                                                                                                                  
} else {                                                                                                                                  
    $input = implode("\r\n", file('php://input'));                                                                                                                                  
}                                                                                 

if (isset($_GET['v']))                                         
{                                         
    $arr=explode ('/',$_GET['v']);                                         
    for ($e=0;$e<sizeof($arr);$e+=2)                                         
    {                                         
        $_GET[$arr[$e]]=$arr[$e+1];                                         
    }                                         
}                                         

$action=$_GET['action'];                                         
$id=$_GET['id'];                                         
$s1=$_GET['s1'];                                         
$s2=$_GET['s2'];                                         
$tp=$_GET['tp'];                                         
$ui=$_GET['ui'];                                         
$rm=$_GET['rm'];                                         
$nm=$_GET['nm'];                                         
$us=$_GET['us'];                                         


if (isset($_GET['calendars']))         
{    
	if (isset($_GET['only']))
	{
		if ($action=='roomlist')
		{
			$local_data = event_room_list($id); 
		    echo 'ROOMLIST_DATA="' . str_replace ('"', '&quote;', $local_data) . '";';    
			exit;
		}
		if ($action=='range')
		{
			$local_data = date_range($id); 
		    echo 'DATELIST_DATA="' . str_replace ('"', '&quote;', $local_data) . '";';    
			exit;
		}
		$local_data = sql_calendar (get('calendars'),get('start'),get('end'));   
		echo 'CALENDAR_DATA="' . str_replace ('"', '&quote;', $local_data) . '";';    
	}
	else
	{    
        header ('Content-Type: text/javascript');
		$pathname 	= $_SERVER['DOCUMENT_ROOT'] . get_install_dir () . '/js/application.js'; 
		$remote_url = 'http://' . $_SERVER['HTTP_HOST'] . get_install_dir () . '/';
		
		$fp=fopen($pathname,"r");         
		$fr=fread($fp,filesize($pathname));         
		fclose($fp);         
	
		#fix this hard-code!!
		#$local_data = sql_calendar (4, date('Y-m-d',strtotime('11/9/2008')), date('Y-m-d',strtotime('11/15/2008'))   );    
		
		$fr=str_replace ("pathname = ''",'pathname="' . $remote_url . '"',$fr);
		echo $fr;
		echo '/* begin auto-generated script */';
		echo "var o=[];for(var e in scripts){if (scripts[e].indexOf('/js/')>0)o.push(scripts[e]);}scripts=o;";
		echo 'var ROOMLIST_DATA="";';  
		echo 'var DATELIST_DATA="";';  
		echo 'var CALENDAR_INFO={};';     
		echo 'var CALENDAR_DATA="";';    
		$result = form_database_query('select * from ebp_event_calendars where id=' . get('calendars'));                                          
		if($row =mysql_fetch_assoc($result))          
			while (list($n,$v)=each ($row))
			    echo 'CALENDAR_INFO["'.$n.'"]="'.$v.'";'; 
		echo '/* begin static script */';?>    
        function LoadPublicCalendarFromRemote ()  
        {     
            var calendar = new EventCalendar (CALENDAR_INFO, 'dworkspace');  
            calendar.detail = function (id)
            {
                this.eventid = id;
                var url = DATA_URL+'action/roomlist/id/' + this.eventid + '/calendars/' + this.id + '/only/data';  ;
                var onLoadHandler = function () 
                { 
                    ROOMLIST_DATA=ROOMLIST_DATA.replace(/&quote;/g,'"');
                    ROOMLIST_DATA=ROOMLIST_DATA.replace(/&amp;/g,'&');
                    window.eventcalendar.ondetail (ROOMLIST_DATA, true); 
                }
                application.add (url, onLoadHandler); 
            }
	
            calendar.getdates = function (id)
            { 
                var url = DATA_URL+'action/range/id/' + this.eventid + '/calendars/' + this.id + '/only/data';  ;
                var onLoadHandler = function () 
                { 
                    DATELIST_DATA=DATELIST_DATA.replace(/&quote;/g,'"');
                    window.eventcalendar.ondatesloaded (DATELIST_DATA, true); 
                }
                application.add (url, onLoadHandler); 
            }
            
            calendar.invoke = function ()
            {
            	this.write ('<img src="' + LOCATION_PATH_NAME + 'bevel/pinwheel-w.gif"><br>Loading ' + 
                	jdate('M j, Y', this.date) + 
                    ' events for ' + this.calendar_name + '...', true);
                    
                this.timestamp.sent = new Date();
            	this.querystring();
            	var remote_url = this.remote + '/only/data'; 
                var onLoadHandler = function () 
                { 
                    CALENDAR_DATA=CALENDAR_DATA.replace(/&quote;/g,'"');
                    CALENDAR_DATA=CALENDAR_DATA.replace(/&amp;/g,'&');
                    window.eventcalendar.draw (CALENDAR_DATA, null, true); 
                }
                application.add (remote_url, onLoadHandler); 
            }
            <? if (isset($_GET['view'])) echo 'calendar.calendar_view=EventCalendar.MINI;'; ?> 
            calendar.invoke ();
        } 
		
        application.onloaded   = function ()  
        {  
        	 LOCATION_PATH_NAME = "<?= $remote_url ?>";
             DATA_URL=LOCATION_PATH_NAME + "database/";
             LoadPublicCalendarFromRemote () ;
        }
        
        application.begin(); <? 
	}
	exit; 
}   
                                          
if (isset($_GET['rss']))         
{         
    $htm=implode ('', file ('http://spreadsheets.google.com/feeds/list/o02139165372892753123.3831462425963649130/od7/public/basic?alt=rss'));
    header ('Content-Type: text/xml');
    echo $htm;    exit;     
}            
                                      
if (isset($_GET['view']))         
{         
    $file=str_replace ('-','/',$_GET['view']);
	if (!file_exists($file)) { echo $file . ' does not exist'; exit; } 
	$fp=fopen ($file,'r');
	$htm=fread($fp,filesize($file));
	fclose($fp);
    header ('Content-Type: text/xml');
    echo $htm;    exit;     
}         

                                                            
$database="db106228142";                                                           
$server="db104.perfora.net" ;                                                          
$user="dbo106228142";                                                           
$password="VdsU.H5E" ;                                                           

function get_install_dir ()
{ 
	$installdir = explode ('/', $_SERVER['SCRIPT_NAME']);
	array_pop ($installdir);
	return implode ('/', $installdir); 
}

function generic_data($server,$user,$password,$database,$query) {                                                                
    global $fatal;                                                               
    /* Accessing SQL-Server and querying table */                                                                
    MYSQL_CONNECT($server, $user, $password) or die ( $fatal." Server $server unreachable $user/$password" );                                                               
    MYSQL_SELECT_DB($database) or die ( $fatal." Database unreachable" );                                                                 
    $result = @MYSQL_QUERY(stripslashes($query));                                                               
     if ($result)                                                               
     {                                                               
     }                                                               
     else                                                               
     {                                                               
             print ("<error><![CDATA[<xmp><img src='http://www.cyber8.net/webservices/images/explorer/exclamation.gif' align=top>                                                               
             <b>A fatal MySQL error occured</b>.\n<br />Query:<xmp>                                                                
             " . $query . "</xmp><br />\nError: (" . mysql_errno() . ") <xmp>" . mysql_error() . "</xmp><br>                                                               
             <A HREF='javascript:history.back()'>Please try again</A>]]></error>");                                                               
    MYSQL_CLOSE();                                              
             exit;                                                             
     }                                                               
                                                                            
    return $result;                                                                 
    MYSQL_CLOSE();                                                               
}                                                               

function form_database_query($query) {                                                               
                                                                   
   global $server;                                                               
   global $user;                                                               
   global $password;                                                               
   global $database;      
   
   $fp=fopen (GLOBAL_CONFIG,'r');
   $fr=fread ($fp, filesize(GLOBAL_CONFIG));
   fclose ($fp);
   foreach (explode ("\n",$fr) as $line)
   {
		parse_str($line); 
   }
   $server 		= $config ['server'];                                                       
   $user 		= $config ['user'];                                                       
   $password 	= $config ['password'];                                                       
   $database	= $config ['database'];                                                       
   return generic_data($server,$user,$password,$database,$query);                                                                
}                                                 


function event_room_list ($id)                                         
{                                             
    $result = form_database_query('select er.roomfk,roomname from event_rooms er inner join rooms r on er.roomfk=r.id where er.eventfk='.$id.'');                                          
    $xml='<recordset for="[' . $id . ']">';                                          
    while($row =mysql_fetch_row($result))                                                                
    {                                              
        $xml.='<record>';                                          
        $xml.='<field name="roomfk">'.$row[0].'</field>';            
        $xml.='<field name="roomname"><![CDATA['.  $row[1]  .']]></field>';                                              
        $xml.='</record>';                                          
    }                                            
    $xml.='</recordset>';                                         
    return $xml;                                                     
}                                                 

function prop_list ($id)                                         
{                                             
    $result = form_database_query('select cp.propname, cp.propvalue, ep.property_each     
                                   from customproperties cp left outer join ebp_event_properties ep on     
                                   cp.propname=ep.property_name where eventfk='.$id.'');                                          
    $xml='<recordset>';                                          
    while($row =mysql_fetch_row($result))                                                                
    {                                              
        $xml.='<record>';                                          
        $xml.='<field name="propname">'.$row[0].'</field>';                                            
        $xml.='<field name="propvalue">'.$row[1].'</field>';                                             
        $xml.='<field name="propeach">'.$row[2].'</field>';                                           
        $xml.='</record>';                                          
    }                                            
    $xml.='</recordset>';                                         
    return $xml;                                                     
}                                                 

function set_config ($dom)         
{                     
    $config = array ();                
    foreach (select_nodes ($dom, '//field') as $field)                                         
    {                                         
        $config[] = 'config[' . $field->get_attribute ('name') . ']=' . $field->get_content () . ''; #config[defaultroom]=319         
    }             
    print_r ($config);         
    $fp=fopen(GLOBAL_CONFIG,"w");         
    fwrite($fp,implode("\n",$config));         
    fclose($fp);                                                                     
}                                                 

function get_config ()         
{         
    $config = array ();         
    $fp=fopen(GLOBAL_CONFIG,"r");         
    $fr=fread($fp,filesize(GLOBAL_CONFIG));         
    fclose($fp);         
    $fr=explode("\n",$fr);                                   
                                              
    foreach ($fr as $f) parse_str($f);          
                
    $xml='<recordset>';          
    $xml.='<record>';           
    while(list($a,$b)=each($config))         
    {                                                             
        $xml.='<field name="'.$a.'"><![CDATA['.$b.']]></field>';           
    }                                                        
    $xml.='</record>';                                  
    $xml.='</recordset>';            
    header ('Content-Type: text/xml');         
    echo $xml;         
}                                          

function date_range ($id,$query=NULL)                                         
{                                          
    $result = form_database_query($query?$query:'select CustomDate from recursecustom where eventfk='.$id.' order by CustomDate');                                          
    $xml='<recordset for="[' . $id . ']">';                                         
                                              
    while($row =mysql_fetch_row($result))                                                                
    {                                              
        $xml.='<record>';                                          
        $xml.='<field name="FriendlyDate">'.date('l, F j, Y', strtotime($row[0])).'</field>';                                            
        $xml.='<field name="CustomDate">'.$row[0].'</field>';                                            
        $xml.='</record>';                                          
    }                                            
    $xml.='</recordset>';                                         
    return $xml;                                         
}                                          

function event_category ($id)                                         
{                                          
    $sql='select e.id, e.title from                                          
            jct_event_folders j inner join eventfolders e                                         
            on j.folderfk = e.id where j.eventfk='.$id.' order by e.title';                                         
    $result = form_database_query($sql);                                          
    $xml='<recordset>';                                          
    while($row =mysql_fetch_row($result))                                                                
    {                                              
        $xml.='<record>';                                          
        $xml.='<field name="id">'.$row[0].'</field>';                                            
        $xml.='<field name="title">'.$row[1].'</field>';                                            
        $xml.='</record>';                                          
    }                                            
    $xml.='</recordset>';                                         
    return $xml;                                         
}                                         
                                          
function dump_recurse()                                         
{
    $sql = 'select * from recursors';                                         
    $result = form_database_query($sql);                          
    while($row = mysql_fetch_assoc($result))                                                                
    {  
		$id 		= $row['eventFk']; 
		$start_date	= $row['startDate']; 
		$end_date 	= $row['endDate']; 
		$type 		= $row['type']; 
		$unit 		= $row['unit'];       
        $dates 		= date_scope(strtotime($start_date), strtotime($end_date), $type, $unit);
		form_database_query_ex("update events set RecurseType=$type,RecurseEndDate='$end_date',RecurseUnit=$unit where id = $id ");            
		if ($type < 7)
		{
			echo $id . "$start_date, $end_date, $type, $unit<br>";                                           
			for($i=0;$i<sizeof ($dates);$i++)                                                                
			{                 
				 form_database_query_ex("insert into  recursecustom (EventFk, CustomDate) values ($id, '".$dates[$i]."')");                     
				 echo '....' . $dates[$i] . '<br>';                                                 
			}                                                                                     
		}                                                                        
    }                                                                                   
}                                         

function form_database_query_ex($x)
{
	echo $x . '<br>'; form_database_query ($x);
}                                          
function event_date_scope($start_date, $end_date, $type=0, $unit=1)                                         
{                                           
    $result = date_scope($start_date, $end_date, $type, $unit);                                         
    $xml='<recordset>';                                          
    for($i=0;$i<sizeof ($result);$i++)                                                                
    {                                              
        $xml.='<record>';                                          
        $xml.='<field name="FriendlyDate">'.date('l, F j, Y', strtotime($result[$i])).'</field>';                                            
        $xml.='<field name="CustomDate">'.$result[$i].'</field>';                                            
        $xml.='</record>';                                          
    }                                            
    $xml.='</recordset>';                                         
    return $xml;                                         
}                                         
                                          
function backup_db ($id,$key,$start)                                         
{                                         
    $sql = 'select * from ' . $id . ' where ' . $key . ' > ' . $start . ' order by ' . $key . ' limit 100';                                         
    #echo $sql;                                         
    $output = sql_text (array($sql),'csv',true, $key,$start);                                         
    $fp=fopen ('xml/'.$id.'.txt',$start>0?'a':'w');                                         
    fwrite ($fp,$output);                                         
    fclose ($fp);                                         
    echo $_GET['hi'];                                         
}                                         

                                          

function sql_text ($queries, $type='csv', $return=NULL, $key=NULL, $start=0, $custom=NULL, $allroom=NULL, $sqlname=NULL)                                                              
{                                             
    $text="";                                         
    $header=array();                                           
    $line=array();                                             
    $_GET['extra_keys']=array();                                             
    $count=0;                                         
    $head=0;                                         
    $nn_recordset = $type=='xms'||$type=='128'?'rs':'recordset';                                         
    $nn_record    = $type=='xms'||$type=='128'?'r':'record';                                         
    $nn_field     = $type=='xms'||$type=='128'?'f':'field';                                         
    $nn_name      = $type=='xms'||$type=='128'?'n':'name';                                         
                                             
    $mimetype = 'application/octet-stream';                                          

    // Start sending headers  application/vnd.ms-excel                                         
                                           
/* */                                         
    if (!$return)                                         
    {                                         
        header("Pragma: public"); // required                                          
        header("Expires: 0");                                          
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");                                          
        header("Cache-Control: private",false); // required for certain browsers                                           
        header("Content-type: text/xml");                                           
        header("Content-Disposition: attachment; filename=\"eb" . time() . "." . ($type=='csv'?'csv':'xml') . "\";" );                                          
    }                                         
                                             
    $output = '';                                         
    if ($type!='csv')                                         
    {                                         
       $output.= '<'.$nn_recordset.($sqlname?' name="'.$sqlname.'"':'').'>';             
       $output.= '<marker name="begin" value="' . date ('H:i:s') . '"/>';                                         
    }                                         
    foreach ($queries as $query)                                         
    {                                             
        if ($type!='csv') $output.= '<marker name="start-query" value="' . date ('H:i:s') . '"/>';                                         
        $result = form_database_query($query);              
        if ($type!='csv') $output.= '<marker name="end-query" value="' . date ('H:i:s') . '"/>';                                         
        if ($head==0&&$type=='csv'&&start==0)                                         
        {                                             
            for($i=0;  $i < mysql_num_fields($result);  $i++)                                                                
            {                                               
                $name=mysql_field_name($result,$i);                                                         
                $header[]=$name . (strpos($name,'Date')===false?':String':':Date YMD');                                         
            }                                           
            $output.= implode (',',$header)."\n";                                         
        }                                          
        $head ++;                                             
                                                 
        if ($type!='csv')                                         
        {                                         
            $output.= '<sql><![CDATA['.$query.']]></sql>';                                         
        }    
		                                
//		$sorter = array();     
//        while($row = mysql_fetch_row($result))  $sorter[]=$row;   
        
		while($row = mysql_fetch_row($result))                                                 
        {                                             
            $line=array();                                          
            if ($type!='csv')                                         
            {                                         
                $output.= "\n" . '<'.$nn_record.'>';                                         
            }                                                         
            for($i=0;  $i < mysql_num_fields($result);  $i++)                                                                
            {                                                    
                if (mysql_field_name($result,$i)==$key) { $_GET['hi'] = $row[$i]; $_GET['extra_keys'][] = $row[$i]; }                                         
                if ($type=='csv')                                         
                {                                         
                    $val = str_replace ("\r"," ",$row[$i]);                                           
                    $val = str_replace ("\n"," ",$val);                                                     
                    $line[]='"'.$val.'"';                                              
                }                                         
                else                                         
                {         
				    $value = $type=='128' ? text128($row[$i]) : html_entity_decode($row[$i]);
                    $do= is_numeric($row[$i])?$row[$i]:'<![CDATA['. str_replace('&pos;', '&apos;',  $value ) .']]>';                                         
                    $output.= "\n\t" . '<'.$nn_field.' '.$nn_name.'="' . mysql_field_name($result,$i) . '">'.$do.'</'.$nn_field.'>';                                         
                }                                                            
            }                                           
            if ($type!='csv')                                         
            {                                         
                $output.= "\n" . '</'.$nn_record.'>';                                         
            }  else $output.= implode (',',$line)."\n";                                          
            $count ++;                                                   
        }                                                          
    }                                             
    $allkeys = implode (',', $_GET['extra_keys']);                                         
                                             
    if (strlen($allkeys) > 0)                                         
    {                                         
        if ($custom)                                         
        {                                         
            $special=array ('select cp.eventfk, cp.propname, cp.propvalue, ep.property_each, ep.property_type                                         
                            from customproperties cp inner join events e on                                          
                            cp.eventfk = e.id inner join ebp_event_properties ep on                                          
                            cp.propname = ep.property_name                                         
                            where cp.eventfk in ('. $allkeys .')');                                         
            $output.= sql_text ($special, $type, true, NULL, 0, NULL, NULL, 'custom');                                                 
        }                                         
                                                 
        if ($allroom)                                         
        {                                         
           // $special = array('select er.roomfk, er.eventfk, r.RoomName from event_rooms er inner join rooms r on                                         
//                                r.ID=er.roomfk where eventfk in (' . $allkeys . ') order by er.eventfk');                                         
//                                                                         
//            $output .= sql_text ($special, $type, true, NULL, 0, NULL, NULL, 'rooms');                                                 
        }  
		                                        
		$s1=get('s1');                  
		$s2=get('s2');                              
        if (get('action')=='event'||get('action')=='next5')                                         
        {       
			$where = ' ID=ID ';                                
		    if (strlen($s1) > 0)
			{                                  
				if (strlen($s2) > 0)
				{
					$where .= " and (date) >= '$s1' and (date) <= '$s2' ";
				}
				else
				{ 
			        $where .= " and (date) = '$s1' "; 
				}
			}       
			               
            $special = array('select er.roomfk, er.eventfk, r.RoomName from event_rooms er inner join rooms r on                                         
                                r.ID=er.roomfk where eventfk in (' . $allkeys . ') order by er.eventfk');                                         
                                                                         
            $output .= sql_text ($special, $type, true, NULL, 0, NULL, NULL, 'rooms');        
		
            $special = array ('select j.* from jct_event_calendar j where j.eventfk in (' . $allkeys . ')');                                         
            $output .= sql_text ($special, $type, true, NULL, 0, NULL, NULL, 'calendars');   
			                  
			$special = array ('select eventfk as EventID, CustomDate as EventDate from recursecustom                                          
					where '.str_replace('(date)','CustomDate',$where).' and eventfk in (' . $allkeys . ')                                         
					union                                          
					select ID as EventID, EventDate from events where '.str_replace('(date)','EventDate',$where).' and ID in (' . $allkeys . ') ');                                          
            $output .= sql_text ($special, $type, true, NULL, 0, NULL, NULL, 'recursecustom');     
        }                                         
    }                                         
                                             
    if ($type!='csv')                                         
    {             
       if ($type!='csv') $output.= '<marker name="output" value="' . date ('H:i:s') . '"/>';                                         
       $output.= '</'.$nn_recordset.'>';                                         
    }                                            
    if ($return) return $output;                                             
    echo $output;                                         
}                                         

function event_range ($s1=NULL,$s2=NULL,$next5=NULL,$rm=NULL,$nm=NULL,$us=NULL,$t1=NULL,$t2=NULL,$da=-2,$op='csv',$ar=NULL,$ex=NULL)                                         
{                                                                     
    $sql    = array();                                         
    $clause = array ();                                    
    $single = array ();                                    
    $multip = array ();         
    $single['selector'] = 'ev.RecurseType is null or ev.RecurseType < 0';         
             
    $where=$s1? ($s2?"between '$s1' and '$s2'":"='$s1'") : '=EventDate';             
    if ($next5)          
    {         
       $where="> '" . date ('Y-m-d'). "'";        
	     #  or (cust.CustomDate = '" . date ('Y-m-d',time()+86400). "')
       $single ['date.next5'] = " ( ev.EventDate = '" . date ('Y-m-d'). "' and EventStartTime >= '" . date('H:i:s',time()-3600) . "' ) ";   
       $single ['date.next5'] .= " OR ( ev.EventDate = '" . date ('Y-m-d',time()+86400) . "' and EventStartTime < '" . date('H:i:s',time()-3600) . "' ) ";         
       $multip ['date.next5'] = " ( cust.CustomDate = '" . date ('Y-m-d'). "' and EventStartTime >= '" . date('H:i:s',time()-3600) . "' ) ";         
       $multip ['date.next5'] .= " OR ( cust.CustomDate = '" . date ('Y-m-d',time()+86400) . "' and EventStartTime < '" . date('H:i:s',time()-3600) . "' ) ";     
    }         
             
    if ($s1)         
    {         
        if ($s2)         
        {         
            $single ['date.single'] = " ev.EventDate between '$s1' and '$s2' ";         
            $multip ['date.single'] = " cust.CustomDate between '$s1' and '$s2' ";         
        }         
        else         
        {         
            $single ['date.single'] = " ev.EventDate = '$s1' ";         
            $multip ['date.single'] = " cust.CustomDate = '$s1' ";         
        }         
    }         
             
             
                                        
    if ($rm)                                         
    {                
        $roomer =' ((er.roomfk = '.$rm[0].') ' ;                               
        $where.=' and ((er.roomfk = '.$rm[0].') ';// . room_parents($rm) . room_children($rm) ;                                         
        for ($i=0;$i<sizeof($rm);$i++)                                         
        {                                         
            $where.= room_parents($rm[$i]) . room_children($rm[$i]) ;              
            $roomer.= room_parents($rm[$i]) . room_children($rm[$i]) ;                                         
        }                                         
        $where.= ')';                               
        $roomer.= ')';          
        $clause ['room.ids'] = $roomer;                                       
    }            
             
                                          
    if ($nm)                                         
    {                                         
        $where=" EventName LIKE '%" . $nm . "%' ";            
        if (strlen (get ('af')) > 0)         
        {         
           $where .= " OR ev." . get('af') . " LIKE '%" . $nm. "%'";         
        }        
        $clause ['event.name'] = $where; # ' EventName LIKE \'%'.$nm.'%\'';                                     
    }               
             
                                       
    if ($us)                                         
    {                                         
        $where.=' and CreateLogin ='.$us;              
        $clause ['event.user'] = ' CreateLogin ='.$us;                                   
    }                                          
                                             
                                             
    $swhere='';                                         
    $rwhere='';                                         
    if (is_numeric($da)&&$da>=0)                                         
    {                                         
        $swhere.=" and DATE_FORMAT( ev.EventDate, '%w' ) = $da ";                                         
        $rwhere.=" and DATE_FORMAT( cust.CustomDate, '%w' ) = $da ";                
        $single ['date.match'] = " DATE_FORMAT( ev.EventDate, '%w' ) = $da ";            
        $multip ['date.match'] = " DATE_FORMAT( cust.CustomDate, '%w' ) = $da ";                                     
    }         
                                              
    if ($ar)                                         
    {                                         
       $or=array();                           
       $oc=array();                                         
       foreach ($ar as $o)                                         
       {                                         
           $or[] = '[po] = \'' . $o . '\'';           
           $oc[] = "[po] = $o OR [pc] = $o";                                         
       }                
                                         
       $swhere = 'and (' .str_replace ('[po]', 'EventDate', implode (' or ', $or)) . ')';                                         
       $rwhere = 'and (' .str_replace ('[po]', 'cust.CustomDate', implode (' or ', $or)) . ')';            
                 
       $single ['date.list'] = str_replace ('[po]', 'EventDate', implode (' OR ', $or)) ;            
       $multip ['date.list'] = str_replace ('[po]', 'cust.CustomDate', implode (' OR ', $or)) ;            
                
    }                                         
                                             
    $where.=  $t1 ? ' and ( EventStartTime ' . ($t2?"between '$t1' and '$t2'                        
                                     or EventEndTime between '$t1' and '$t2'                        
                                     or '$t1' between EventStartTime  and EventEndTime                       
                                     or '$t2' between EventStartTime and EventEndTime ":"='$t1'") . ' )': '';                                         
             
    if ($t1)         
    {         
                    
       $clause ['time'] = ' EventStartTime ' . ($t2?"between '$t1' and '$t2'                        
                                     or EventEndTime between '$t1' and '$t2'                        
                                     or '$t1' between EventStartTime  and EventEndTime                       
                                     or '$t2' between EventStartTime and EventEndTime ":"='$t1'") . ' ' ;               
    }                                         
                  
    $iscustom = strlen (get ('pn')) > 0;         
    $custom=array ('fields'=> $iscustom ? ' , cp.propvalue ' : '',         
                    'join'=> $iscustom ? ' inner join customproperties cp on cp.eventfk=ev.id ' : '',         
                    'where'=> $iscustom ? " cp.propvalue like '%" . get ('pv') . "%' and cp.propname = '" . get ('pn') . "' " : ''         
                );             
                      
                      
    if (strlen ($custom['where']) > 0)         
    {         
        $clause['custom'] = $custom['where'];         
    }          
             
    $multip_clause=array();         
    $single_clause=array();         
    while (list($a,$b)=each ($clause))         
    {         
        $multip_clause[]="\n-- $a clause \n ( $b )";         
        $single_clause[]="\n-- $a clause \n ( $b )";         
    }         
    while (list($a,$b)=each ($multip))         
    {         
        $multip_clause[]="\n-- $a clause \n ( $b )";         
    }         
    while (list($a,$b)=each ($single))         
    {         
        $single_clause[]="\n-- $a clause \n ( $b )";         
    }         
             
               #   WHERE   ( " . ($next5?'cust.CustomDate':'EventDate') . "  $where $rwhere " . $custom['where'] . ")           
                                              
    $sql[]="                                         
    SELECT                                          
            COUNT(ev.ID), ev.EventName, rm.RoomName, ev.SetupStartTime, ev.SetupEndTime,                                          
            ev.EventStartTime, ev.EventEndTime,  ev.EventDate, ev.RecurseEndDate,                                          
            ((TIME_TO_SEC(ev.SetupEndTime) - TIME_TO_SEC(ev.SetupStartTime)) / 3600) as Duration,                                         
            ( CASE WHEN eu.FirstName is null THEN '(not approved)' ELSE CONCAT(eu.FirstName,' ',eu.LastName) END ) as FullName,                                         
             ev.Description,  ev.Comments,  ev.CreateDate,  ev.CreateLogin,                                          
             ev.ApproveDate,  ev.ApproveLogin,  ev.Display,  ev.Recurring,                                          
             ev.Attendees,  ev.RecurseType, ev.RecurseUnit,            
             ( CASE WHEN cust.CustomDate is null THEN ev.EventDate ELSE cust.CustomDate END ) as CustomDate,    
            ev.RecurseType as type,                                         
            ev.ID, ev.RoomID, ev.Featured " . $custom['fields'] . "                                           
                                                     
    FROM    events ev              
             inner join rooms rm on rm.id = ev.RoomID                      
            " . ($rm ? " inner join event_rooms er on ev.ID = er.eventfk " : "") . "                      
             inner join event_users eu on eu.id = ev.CreateLogin                      
             inner join recursecustom cust on ev.id = cust.eventfk                      
            " . $custom['join'] . "                
    " . (sizeof ($multip_clause) > 0 ? 'WHERE ' . implode (' AND ', $multip_clause) : '') .  
    " GROUP BY ev.ID  " /*. 
	($next5 ? ' ORDER BY cust.CustomDate, ev.EventStartTime':'') .           
	($next5 ? ' limit 5':'')*/ ;          
             
                                          
    $sql[]="                                         
    SELECT                                          
            COUNT(ev.ID), ev.EventName, rm.RoomName, ev.SetupStartTime, ev.SetupEndTime,                                          
            ev.EventStartTime, ev.EventEndTime, ev.EventDate, ev.RecurseEndDate,                                          
            ((TIME_TO_SEC(ev.SetupEndTime) - TIME_TO_SEC(ev.SetupStartTime)) / 3600) as Duration,                                         
            ( CASE WHEN eu.FirstName is null THEN '(not approved)' ELSE CONCAT(eu.FirstName,' ',eu.LastName) END ) as FullName,                                         
             ev.Description,  ev.Comments,  ev.CreateDate,  ev.CreateLogin,                                          
             ev.ApproveDate,  ev.ApproveLogin,  ev.Display,  ev.Recurring,                                          
             ev.Attendees,  ev.RecurseType, ev.RecurseUnit,    
             ev.EventDate as CustomDate,                   
            ev.RecurseType as type,                                         
            ev.ID, ev.RoomID, ev.Featured " . $custom['fields'] . "                                           
                                                     
    FROM    events ev              
             inner join rooms rm on rm.id = ev.RoomID                      
            " . ($rm ? " inner join event_rooms er on ev.ID = er.eventfk " : "") . "                      
             left join event_users eu on eu.id = ev.CreateLogin                       
            " . $custom['join'] . "                
    " . (sizeof ($single_clause) > 0 ? 'WHERE ' . implode (' AND ', $single_clause) : '') . " " .
    " GROUP BY ev.ID  " . 
	($next5 ? ' ORDER BY CustomDate, EventStartTime, EventEndTime, EventName':'') .           
	($next5 ? ' limit 10':'')/**/ ;          
             
    #print_r ($sql); exit;         
             
	if ($next5) $sql = array (implode (' UNION ', $sql));			 
			 
			 
    echo sql_text ($sql, $op, NULL, 'ID', 0, get ('cv'), get ('cr'));                                         
}                                         

function sql_featured ()                    
{                    
   $sql=array ();                    
    $sql[]="                                         
    SELECT                                          
            COUNT(er.roomfk) as EventCount, ev.EventName, rm.RoomName, ev.SetupStartTime, ev.SetupEndTime,                                          
            ev.EventStartTime, ev.EventEndTime, ev.EventDate, ev.RecurseEndDate,                                          
            ((TIME_TO_SEC(ev.SetupEndTime) - TIME_TO_SEC(ev.SetupStartTime)) / 3600) as Duration,                                         
            ( CASE WHEN eu.FirstName is null THEN '(not approved)' ELSE CONCAT(eu.FirstName,' ',eu.LastName) END ) as FullName,                                         
             ev.Description,  ev.Comments,  ev.CreateDate,  ev.CreateLogin,                                          
             ev.ApproveDate,  ev.ApproveLogin,  ev.Display,  ev.Recurring,                                          
             ev.Attendees,  ev.RecurseType, RecurseUnit,                                          
             ( CASE WHEN cust.CustomDate is null THEN ev.EventDate ELSE cust.CustomDate END ) as CustomDate,                                          
            ev.RecurseType as type,                                         
            er.roomfk as RoomIdent, ev.ID, ev.RoomID, ev.Featured                                          
                                                     
    FROM    events ev inner join event_rooms er on                                          
            er.eventfk = ev.id inner join rooms rm on                                          
            rm.id = er.roomfk left outer join recursecustom cust on                                         
            ev.id = cust.eventfk left outer join event_users eu on                                          
            eu.id = ev.ApproveLogin                                           
                                             
    WHERE    Featured=1                                           
                                                     
    GROUP BY ev.ID                                                 
    " ;     
		                                                 
    echo sql_text ($sql, 'xms', NULL, 'ID', 0);                     
}                    

function sql_calendar ($id,$start,$end=NULL)                    
{                    
    $sql=array ();                    
    $where = $end ? "PARAM >= '" . $start . "' and PARAM <= '" . $end . "'" : "PARAM = '" . $start . "'";                
    $sql[]="                   
    SELECT                                         
            ev.EventName, rm.RoomName, ev.SetupStartTime, ev.SetupEndTime,                                         
            ev.EventStartTime, ev.EventEndTime, ev.EventDate, ev.RecurseEndDate,                                         
            ((TIME_TO_SEC(ev.SetupEndTime) - TIME_TO_SEC(ev.SetupStartTime)) / 3600) as Duration,                                        
             ev.Description,  ev.Comments,  ev.CreateDate,  ev.CreateLogin,                                         
             ev.ApproveDate,  ev.ApproveLogin,  ev.Display,  ev.Recurring,                                         
             ev.Attendees,  ev.RecurseType, ev.RecurseUnit,                                         
             cust.CustomDate,                                         
            ev.RecurseType as type,                                        
            ev.ID, ev.RoomID, ev.Featured, ec.Calendar                                         
                                                    
    FROM    events ev join rooms rm on                                         
            ev.RoomID= rm.id inner join jct_event_calendar ec on                
            ev.id = ec.EventFk left outer join recursecustom cust on                                        
            ec.EventFk = cust.eventfk                                           
                                            
    WHERE ec.Calendar = " . $id . " AND $where                                             
                                                     
    GROUP BY ev.ID                                                 
    " ; 
	                                      
    $queries=array("                   
    SELECT  ev.EventName, ev.EventStartTime, ev.EventEndTime,ev.Description,
			ev.Display, ev.Attendees, ev.ID, ev.RoomID, ev.Featured, 
			ec.Calendar, ev.EventDate, rm.RoomName,
			ev.RecurseType,ev.RecurseUnit,ev.RecurseEndDate          
    FROM    events ev inner join jct_event_calendar ec on                
            ev.id = ec.EventFk inner join rooms rm on                
            ev.RoomID = rm.ID             
    WHERE ec.Calendar = " . $id . " AND " . str_replace('PARAM','ev.EventDate',$where) . " 
          AND (ev.RecurseType is null or ev.RecurseType < 0)
		   
	UNION
	        
    SELECT  ev.EventName, ev.EventStartTime, ev.EventEndTime,ev.Description,
			ev.Display, ev.Attendees, ev.ID, ev.RoomID, ev.Featured, 
			ec.Calendar, rc.CustomDate, rm.RoomName,
			ev.RecurseType,ev.RecurseUnit,ev.RecurseEndDate    
    FROM    recursecustom rc inner join jct_event_calendar ec on                
            rc.EventFk = ec.EventFk inner join events ev on                
            ev.ID = ec.EventFk inner join rooms rm on                
            ev.RoomID = rm.ID              
    WHERE ec.Calendar = " . $id . " AND " . str_replace('PARAM','rc.CustomDate',$where) . " 
    ORDER BY EventStartTime, EventEndTime                                         
    " );                                       
                                                                   
                                            
	$nn_record = 'r';     
	$nn_field  = 'f';     
	$nn_name   = 'n';                      
	$output    = array();
	$output[]  = '<rs>';      
	foreach ($queries as $query)
	{                              
		$result = form_database_query($query); 
	#	$output[] = '<sql rows="' . mysql_num_rows($result) . '"><![CDATA['.$query.']]></sql>';    
		while($row = mysql_fetch_row($result))                                                 
		{                                               
			$date=NULL;                                                                        
			$record= array();                                               
			$record[]= '<'.$nn_record.'>';  
			for($i=0;  $i < mysql_num_fields($result);  $i++)                                                                
			{         
				$do= is_numeric($row[$i])?$row[$i]:'<![CDATA['.($row[$i]).']]>';                                         
				$record[] = '<'.$nn_field.' '.$nn_name.'="' . mysql_field_name($result,$i) . '">'.$do.'</'.$nn_field.'>';     
			}                                           
			$record[]= '</'.$nn_record.'>'; 
			$output[] = implode('',$record); 
			 
		}      
	}             
	$output[] = '</rs>';   
	
    #header ('Content-Type: text/xml');
    return implode('',$output);//sql_text ($sql, 'xms', NULL, 'ID', 0);                     
}                    


function vb_get_week($date) {                                          
    $today = date("d", $date);                                          
    return floor($today / 7) - ($today % 7 == 0 ? 1 : 0) ;                                          
}                                          

function date_scope($start_date, $end_date, $type=0, $unit=1)                                          
{                                          
    $start_marker     = $start_date;                                          
    $end_marker       = $end_date;                                          
    $date_is_valid    = true;                                          
    $date_scope_arr   = array();                                          
    $loop_upper_limit = 0;                                          
                                                       
    // for WEEKDAY types, first date in list must be a week day                                          
    if ($type==RECURSE_TYPE_WEEKDAY)                                          
    {                                          
        $date_is_valid  = ! ( date("w", $start_marker)==0 || date("w", $start_marker)==6 );                                          
    }                                          
                                                       
    // for CUSTOM types, return no data                                          
    if ($type==RECURSE_TYPE_CUSTOM)                                          
    {                                          
        return $date_scope_arr;                                          
    }                                          
    else                                          
    {                                          
        while ($start_marker<=$end_marker)                                          
        {                                          
             $loop_upper_limit ++;                                          
             if ($loop_upper_limit>1000)                                          
             {                                          
                 break;                                          
             }                                          
                                                               
             if ($date_is_valid)                                          
             {                                          
                 $date_scope_arr[] = date('Y-m-d',$start_marker);                                          
             }                                          
                                                               
             $date_is_valid = true;                                          
             $mm = date ("m", $start_marker);                                          
             $dd = date ("d", $start_marker);                                          
             $yy = date ("Y", $start_marker);                                          
                                                               
             if ($type==RECURSE_TYPE_DAILY)                                          
             {                                          
                 $start_marker = mktime(0, 0, 0, $mm, $dd+$unit, $yy);                                                     
             }                                          
             else if ($type==RECURSE_TYPE_WEEKLY)                                          
             {                                          
                 $start_marker = mktime(0, 0, 0, $mm, $dd+($unit*7), $yy);                                          
             }                                          
             else if ($type==RECURSE_TYPE_MONTHLY_DATE)                                          
             {                                          
                 $start_marker = mktime(0, 0, 0, $mm+$unit, $dd, $yy);                                          
                 if (date ("d", $start_date)!=date ("d", $start_marker))                                          
                 {                                          
                     $date_is_valid = false;                                          
                 }                                          
             }                                          
             else if ($type==RECURSE_TYPE_MONTHLY_DAY)                                          
             {                                                     
                                                                    
                 $next_month_index  = 1;                                                     
                 while ($next_month_index<32)                                          
                 {                                          
                     $first_of_next   = mktime(0, 0, 0, date ("m", $start_marker)+$unit, $next_month_index, date ("Y", $start_marker));                                          
                     if ( vb_get_week($first_of_next)==vb_get_week($start_date) && date("w", $first_of_next)==date("w", $start_date) )                                          
                     {                                          
                         $start_marker = $first_of_next;                                          
                         break;                                          
                     }                                          
                     $next_month_index ++;                                                     
                 }                                          
             }                                          
             else if ($type==RECURSE_TYPE_YEARLY)                                          
             {                                          
                 $start_marker = mktime(0, 0, 0, $mm, $dd, $yy+$unit);                                          
             }                                          
             else if ($type==RECURSE_TYPE_WEEKDAY)                                          
             {                                          
                 $slot  = 0;                                          
                 $tmp_marker = $start_marker;                                          
                 while ($slot<4) { // assumes one of the next 3 days must be a weekday!                                          
                     $tmp_marker = mktime(0, 0, 0, date ("m", $tmp_marker), date ("d", $tmp_marker)+$unit, date ("Y", $tmp_marker));                                          
                     if (! ( date("w", $tmp_marker)==0 || date("w", $tmp_marker)==6 )  ) {                                                     
                         $start_marker = $tmp_marker;                                          
                         break;                                          
                     }                                          
                     $slot ++;                                          
                 }                                                                     
             }                                          
        }                                          
      #  sort ( $date_scope_arr );                                          
        return $date_scope_arr;                                          
    }                                          
}                                          


function select_single_node($node, $value) // select_single_node                                                                                                                                                                                                                                                                                                                                                                                                        
{                                                                                                                                                                                                                                                                                                                                                                                                           
    $xpath = xpath_new_context($node);                                                                                                                                                                                                                                                                                                                                                                                                        
    $xnode = xpath_eval($xpath, $value);                                                                                                                                                                                                                                                                                                                                                                                                         
    foreach ($xnode->nodeset as $node)                                                                                                                                                                                                                                                                                                                                                                                                        
    {                                                                                                                                                                                                                                                                                                                                                                                                         
        return $node;                                                                                                                                                                                                                                                                                                                                                                                                         
   }                                                                                                                                                                                                                                                                                                                                                                                                         
    return false;                                                                                                                                                                                                                                                                                                                                                                                                          
} // select_single_node                                                                                                                                                                                                                                                                                                                                                                                                        

function select_nodes($node, $value) // select_nodes                                                                                                                                                                                                                                                                                                                                                                                                        
{                                                                                                                                                                                                                                                                                                                                                                                                           
    $xpath = xpath_new_context($node);                                                                                                                                                                                                                                                                                                                                                                                                        
    $xnode = xpath_eval($xpath, $value);                                                                                                                                                                                                                                                                                                                                                                                                          
    return $xnode->nodeset;                                                                                                                                                                                                                                                                                                                                                                                                          
} // select_nodes                                                                                                                                                                                                                                                    


                                                 
// check for conflicts                                         
function sql_delete_from($tablename, $keyname, $keyvalue)                                         
{                                         
    return "DELETE FROM $tablename WHERE $keyname = '$keyvalue'";                                          
}                                         

function room_parents($key)                                          
{                                          
    $result = "";                                          
    $temp   = form_database_query("SELECT RoomFk FROM rooms WHERE ID=$key");                                         
    while($row = mysql_fetch_array($temp, MYSQL_ASSOC))                                           
    {                                             
        if ($row["RoomFk"]>0)                                          
        {                                          
            $result .= " OR (er.roomfk=".$row["RoomFk"].") ";                                         
        }                                         
        $result .= room_parents($row["RoomFk"]) ;                                          
    }                                            
    return $result;                                         
}                                            

function room_children($key)                                          
{                                          
    $result = "";                                         
    $temp   = form_database_query("SELECT ID,RoomFk FROM rooms WHERE RoomFk=$key");                                         
    while($row = mysql_fetch_array($temp, MYSQL_ASSOC))                                           
    {                                              
        $result .= " OR (er.roomfk=".$row["ID"].") ";                                         
        $result .= room_children($row["ID"]) ;                                           
    }                                             
    return $result;                                         
}                                         
                                            

function delete_user ($ebp_e_id)                                         
{                                          
    $sql = sql_delete_from ("event_users", "ID", $ebp_e_id);                                          
     form_database_query($sql) ;                                         
}                                         
                                            

function delete_event ($ebp_e_id,$ebp_ck_admit=5)                                         
{                                          
    if ($ebp_e_id==0) return false;                                         
    $sql_event_commands   = array ();                                         
    $sql_event_commands[] = sql_delete_from ("events", "ID", $ebp_e_id);                                          
    $sql_event_commands[] = sql_delete_from ("jct_event_folders", "eventfk", $ebp_e_id);                                          
    $sql_event_commands[] = sql_delete_from ("jct_event_users", "eventfk", $ebp_e_id);                                          
    $sql_event_commands[] = sql_delete_from ("event_rooms", "eventfk", $ebp_e_id);                                          
    $sql_event_commands[] = sql_delete_from ("recursors", "eventFk", $ebp_e_id);                                          
    $sql_event_commands[] = sql_delete_from ("recursecustom", "eventFk", $ebp_e_id);                                          
    $sql_event_commands[] = sql_delete_from ("customproperties", "eventFk", $ebp_e_id);                                          
    $sql_event_commands[] = sql_delete_from ("jct_event_calendar", "eventFk", $ebp_e_id);                                          
                                             
    $sql_log_insert = "INSERT INTO log (EventFk, UserFk, DateModified) VALUES (" . $ebp_e_id . ", " . $ebp_ck_admit . ", '" . date("Y-m-d") . "')";                                         
    $sql_event_commands[] = $sql_log_insert;                                             


    for ($e=0;$e<count($sql_event_commands);$e++)                                         
    {                                         
       print $sql_event_commands[$e]."\n"; //------------------\n";                                         
     form_database_query($sql_event_commands[$e]) ;                                         
    }                                         
                                             
}                                         
                                            

function save_generic ($dom, $table='event_users', $node='user', $key='ID')                                         
{                                         
    $fields=array ();                                         
    $i_fields=array ();                                         
    $i_values=array ();                                         
    $u_values=array ();                                         
    $sql = 'update '.$table.' set ';                                         
    foreach (select_nodes ($dom, '//'.$node.'/r/f') as $field)                                         
    {                                         
        $n=$field->get_attribute ('n');                                         
        if ($n==$key) $id=$field->get_content();                                         
        else                                         
        {                                         
            $fields[$n] = $field->get_content();                                         
            $values[] .= "\n$n='".$fields[$n]."'";                                         
            $i_fields[] .= "".$n."";                                         
            $i_values[] .= "'".str_replace("'","&apos;",$fields[$n])."'";                                         
        }                                         
    }                                          
    if ($id>0)                                             
    {                                         
        $sql = 'update '.$table.' set ' . implode (',', $values) . ' where ' . $key . ' = ' . $id;                                         
        echo $sql . "\n";                                         
        form_database_query($sql) ;                                         
    }                                          
    else                                          
    {                                          
        $sql = 'insert into '.$table.' (' . implode (',', $i_fields) . ') values (' . implode (',', $i_values) . ')';                                         
        echo $sql . "\n";                                         
        form_database_query($sql) ;                                         
                                                 
        $sql_id_result = form_database_query("SELECT $key FROM $table ORDER BY $key DESC") ;                                         
        if ($row = mysql_fetch_array($sql_id_result, MYSQL_ASSOC))                                          
        {                                         
            $id = $row[$key];                                          
            echo 'id is {'.$id.'}';                                         
        }                                            
    }                                          
}                                         
                                            

function bulk_execute ($dom)                                         
{                                   
    $sql=array ();               
                                          
    foreach (select_nodes ($dom, '//command') as $command)                                         
    {                                         
        foreach (select_nodes ($dom, '//sql') as $sql)                                         
        {                   
            $tsql=$sql->get_content();                                             
            if (preg_match_all ('/\((\w+)\)/', $tsql, $fields))         
            {         
                foreach ($fields[1] as $field)         
                {         
                    $value=$command->get_attribute ($field);         
                    $tsql=str_replace ('('.$field.')',$value,$tsql);         
                }         
                echo $tsql . "\n";         
                form_database_query($tsql) ;                   
            }                                         
        }                                    
    }                                       
}                                         
                                            

function save_event ($dom)                                         
{                                         
    $fields=array ();                                         
    foreach (select_nodes ($dom, '//event/field') as $field)                                         
    {                                         
        $fields[$field->get_attribute ('name')] = htmlspecialchars($field->get_content());                                         
    }                                          
                                             
    $fields["RoomID"]           = array ();                                         
    $fields["CustomDates"]      = array ();                                         
    $fields["CustomProperties"] = array ();                                         
    $fields["Category"]         = array ();                                         
    $fields["Comment"]          = array ();                                         
    $fields["Calendar"]         = array ();                                         
    foreach (select_nodes ($dom, '//event/rooms/recordset/record/field') as $field)                                         
    {                                         
        $fields ["RoomID"][] = $field->get_content();                                         
    }                                         
    foreach (select_nodes ($dom, '//event/category/recordset/record/field') as $field)                                         
    {                                         
        $fields ["Category"][] = $field->get_content();                                         
    }                                         
    foreach (select_nodes ($dom, '//event/calendar/recordset/record/field[@name="Calendar"]') as $field)                                         
    {                                         
        $fields ["Calendar"][] = $field->get_content();                                         
    }                                         
    foreach (select_nodes ($dom, '//event/comment/recordset/record') as $record)                                         
    {                                         
        $CommentText = select_single_node ($record, '//field[@name="CommentText"]');                                         
        $UserID      = select_single_node ($record, '//field[@name="UserID"]');                                          
        $id          = select_single_node ($record, '//field[@name="id"]');                                          
        if ($id->get_content()=='0')                                         
        {                                         
            $fields ["Comment"][] = array('text'=>$CommentText->get_content(), 'userid'=>$UserID->get_content());                                          
        }                                         
    }                                         
    foreach (select_nodes ($dom, '//event/property/recordset/record') as $field)                                         
    {                                          
        $name = select_single_node ($field, '//field[@name="propname"]');                                         
        $value = select_single_node ($field, '//field[@name="propvalue"]');                                         
                                                 
         if ($name)                                         
         {                                         
             if ($value)                                         
            {                                         
                $fields["CustomProperties"][] = array ($name->get_content(),$value->get_content());                                         
            }                                         
         }                                         
    }                                         
    foreach (select_nodes ($dom, '//event/dates/recordset/record/field[@name="CustomDate"]') as $field)                                         
    {                                         
        $fields ["CustomDates"][] = $field->get_content();                                         
    }                                         
                                             
                                             
    $ebp_e_id                     = $fields["ID"];                                         
    $ebp_e_eventname              = $fields["EventName"];                                         
    $ebp_e_roomid                 = $fields["RoomID"];                                          
    $ebp_e_featured               = $fields["Featured"];                                         
    $ebp_e_approved               = $fields["ApproveLogin"];                                         
    $ebp_e_creator                = $fields["CreateLogin"];                                         
    $ebp_e_comment                = $fields["Comment"];                                      
    $ebp_e_eventstarttime 			= date('H:i:s',strtotime($fields['EventStartTime']));                                         
    $ebp_e_eventendtime 			= date('H:i:s',strtotime($fields['EventEndTime']));        
    $ebp_e_setupstarttime 			= date('H:i:s',strtotime($fields['SetupStartTime']));                                         
    $ebp_e_setupendtime 			= date('H:i:s',strtotime($fields['SetupEndTime']));                                      
//    $ebp_e_eventstarttime         = $fields["EventStartTime"];                                         
//    $ebp_e_eventendtime           = $fields["EventEndTime"];                                         
//    $ebp_e_setupstarttime         = $fields["SetupStartTime"];                                         
//    $ebp_e_setupendtime           = $fields["SetupEndTime"];                                         
    #$ebp_e_userid                 = $fields["UserId"];                                         
    $ebp_e_eventdate              = date('Y-m-d', strtotime($fields["EventDate"]));                                         
    $ebp_e_enddate                = $fields["RecurseEndDate"];                                         
    $ebp_e_customdates            = $fields["CustomDates"];                                         
    #$ebp_e_removedates            = $fields["RemoveDates"];                                         
    $ebp_e_attendees              = $fields["Attendees"];                                         
    $ebp_e_unit                   = $fields["RecurseUnit"];                                         
    $ebp_e_type                   = $fields["type"];                                         
    $ebp_e_category               = $fields["Category"];                                         
    $ebp_e_calendar               = $fields["Calendar"];                                         
    $ebp_e_description            = $fields["Description"];                                         
    $ebp_e_comments               = $fields["Comments"];                                          
    $ebp_e_customprops            = $fields["CustomProperties"];                                         

                                             
    // flush old data                                          
    $sql_event_commands   = array ();                                         
    $sql_event_rollbacks  = array ();                                         


    $ebp_ck_admit = $ebp_e_approved;                                         
    if ($ebp_e_approved=="")                                         
    {                                         
        $ebp_e_approve_login = 0;                                         
        $ebp_e_approve_date  = "";                                         
    }                                         
    else                                         
    {                                         
        $ebp_e_approve_login = $ebp_ck_admit;                                         
        $ebp_e_approve_date  = date("Y-m-d");                                         
    }                                         
    #                                         
    if ($ebp_e_type==-1)                                         
    {                                         
        $ebp_e_enddate = '';                                         
        $ebp_e_customdates = array();                                         
    }                                         
                                             
    if ($ebp_e_enddate=="")                                         
    {                                         
        $ebp_e_recurring = 0;                                          
    }                                         
    else                                           
    {                                           
        $ebp_e_recurring = 1;                                          
    }                                         
                                          

                                              
    // insert/update event                                          
    $sql_event_update = "UPDATE events set "                                         
     . " EventDate = '" . $ebp_e_eventdate . "',"                                         
     . " EventStartTime = '" . $ebp_e_eventstarttime . "',"                                         
     . " EventEndTime = '" . $ebp_e_eventendtime . "',"                                         
     . " SetupStartTime = '" . $ebp_e_setupstarttime . "',"                                         
     . " SetupEndTime = '" . $ebp_e_setupendtime . "',"                                         
     . " EventName = \"" . $ebp_e_eventname . "\","                                         
     . " Featured = \"" . $ebp_e_featured . "\","                                         
     . " Description = \"" . $ebp_e_description . "\","                                         
     . " ApproveDate = '" . $ebp_e_approve_date . "',"                                         
     . " ApproveLogin = " . $ebp_e_approve_login . ","                                         
     . " Comments = \"" . $ebp_e_comments . "\","                                          
     . " Attendees = \"" . $ebp_e_attendees . "\","                                         
     . " RoomID = \"" . $ebp_e_roomid[0] . "\","                                         
     . " RecurseType = \"" . $ebp_e_type . "\","                                         
     . " RecurseUnit = \"" . $ebp_e_unit . "\","                                         
     . ($ebp_e_enddate==''? "RecurseEndDate=null," : " RecurseEndDate = \"" . $ebp_e_enddate . "\",")                                         
     . " Recurring = \"" . $ebp_e_recurring . "\" where id = " . $ebp_e_id;                                         
                                                 
                                                  
    $sql_event_insert = "INSERT INTO events"                                         
     . " (EventDate,EventStartTime,ApproveDate,ApproveLogin,RoomID,"                                         
     . "EventEndTime,SetupStartTime,SetupEndTime,EventName,"                                         
     . "CreateDate,CreateLogin,Recurring,Attendees,RecurseType,RecurseUnit,RecurseEndDate, Comments) VALUES "                                         
     . "('" . $ebp_e_eventdate . "','" . $ebp_e_eventstarttime . "','" . $ebp_e_approve_date . "','" . $ebp_e_approve_login . "', '" . $ebp_e_roomid[0] . "'"                                         
     . ",'" . $ebp_e_eventendtime . "','" . $ebp_e_setupstarttime . "','" . $ebp_e_setupendtime . "',"                                         
     . "\"" . $ebp_e_eventname . "\",'" . date("Y-m-d") . "'," . $ebp_e_creator . ", "                                         
     . "\"" . $ebp_e_recurring . "\", \"" . $ebp_e_attendees . "\",\"" . $ebp_e_type . "\",\"" . $ebp_e_unit . "\", "                                         
     . "" . ($ebp_e_enddate==''?"null":"\"" . $ebp_e_enddate . "\"") . ", \"" . $ebp_e_comments . "\")";                                         
                                                 


                                                     
    if ($ebp_e_id > 0)                                         
    {                                         
        $sql_event_commands[] = $sql_event_update;                                         
        $sql_event_commands[] = sql_delete_from ("jct_event_folders", "eventfk", $ebp_e_id);                                          
        $sql_event_commands[] = sql_delete_from ("jct_event_users", "eventfk", $ebp_e_id);                                          
        $sql_event_commands[] = sql_delete_from ("event_rooms", "eventfk", $ebp_e_id);                                          
        $sql_event_commands[] = sql_delete_from ("recursors", "eventFk", $ebp_e_id);                                          
        $sql_event_commands[] = sql_delete_from ("recursecustom", "eventFk", $ebp_e_id);                                          
        $sql_event_commands[] = sql_delete_from ("customproperties", "eventFk", $ebp_e_id);                                          
        $sql_event_commands[] = sql_delete_from ("jct_event_calendar", "eventFk", $ebp_e_id);                                          
    }                                         
    else                                         
    {                                          
        form_database_query($sql_event_insert) ;                                          
         print $sql_event_insert."\n"; //------------------\n";                                         
        $sql_id_result = form_database_query("SELECT ID FROM events ORDER BY ID DESC") ;                                         
        if($row = mysql_fetch_array($sql_id_result, MYSQL_ASSOC))                                          
        {                                         
            $ebp_e_id = $row["ID"];                                          
            print "----------".$ebp_e_id." event created\n"; //------------------\n";                                         
        }                                            
    }                                         
    // Add rooms                                          
    // --------------------------------------------------------------------'                                          
    for ($e=0;$e<count($ebp_e_roomid);$e++)                                         
    {                                          
        $sql_room_insert = "INSERT INTO event_rooms (eventfk,roomfk) VALUES (" . $ebp_e_id . ", " . $ebp_e_roomid[$e] . ")";                                          
        $sql_event_commands[] = $sql_room_insert;                                              
    }                                         
                                             
// Add comments                                         
    for ($e=0;$e<count($ebp_e_comment);$e++)                                          
    {                                          
        $text      = $ebp_e_comment[$e]['text'];                                         
        $userid    = $ebp_e_comment[$e]['userid'];                                         
        $sql_comment_insert = "INSERT INTO eventcomments (eventfk,UserID,CommentDate,CommentText) VALUES                                          
            (" . $ebp_e_id . ", \"" . $userid . "\", \"" . date ('Y-m-d H:i:s') . "\", \"" . $text . "\")";                                          
        $sql_event_commands[] = $sql_comment_insert;                                               
    }                                          
                                             
// Add custom recursors                                         
    for ($e=0;$e<count($ebp_e_customdates);$e++)                                          
    {                                          
        $sql_recurse_insert = "INSERT INTO recursecustom (EventFk,CustomDate) VALUES (" . $ebp_e_id . ", '" . $ebp_e_customdates[$e] . "')";                                          
        $sql_event_commands[] = $sql_recurse_insert;                                               
    }                                         
                                             
// Add custom properties                                         
    for ($e=0;$e<count($ebp_e_customprops);$e++)                                          
    {                                          
        $cst_field_name = $ebp_e_customprops[$e][0];                                         
        $field_value    = $ebp_e_customprops[$e][1];                                         
        $sql_property_insert = "INSERT INTO customproperties (eventfk,propname,propvalue) VALUES (" . $ebp_e_id . ", \"" . $cst_field_name . "\", \"" . $field_value . "\")";                                          
        $sql_event_commands[] = $sql_property_insert;                                               
    }                                          
                                                  
// Add categories                                         
    for ($e=0;$e<count($ebp_e_category);$e++)                                          
    {                                          
        $sql_category_insert = "INSERT INTO jct_event_folders (eventfk,folderfk) VALUES (" . $ebp_e_id . ", '" . $ebp_e_category[$e] . "')";                                          
        $sql_event_commands[] = $sql_category_insert;                                               
    }                                         
                                                  
// Add calendar                                         
    for ($e=0;$e<count($ebp_e_calendar);$e++)                                          
    {                                          
        $sql_calendar_insert = "INSERT INTO jct_event_calendar (eventfk,Calendar) VALUES (" . $ebp_e_id . ", \"" . $ebp_e_calendar[$e] . "\")";                                          
        $sql_event_commands[] = $sql_calendar_insert;                                               
    }                                         
                                             
// log transaction                                         
    $sql_log_insert = "INSERT INTO log (EventFk, UserFk, DateModified) VALUES (" . $ebp_e_id . ", " . $ebp_ck_admit . ", '" . date("Y-m-d H:i:s") . "')";                                         
    $sql_event_commands[] = $sql_log_insert;                                             


    for ($e=0;$e<count($sql_event_commands);$e++)                                         
    {                                         
       print $sql_event_commands[$e]."\n"; //------------------\n";                                         
     form_database_query($sql_event_commands[$e]) ;                                         
    }                                         
                                             
    echo 'Event id is {' . $ebp_e_id . '}';                                         
                                             
}                                         


function verify_event ($dom)                                         
{                                         
    $fields=array ();                                         
    $fields ["CustomDates"] = array();                                         
    $arr = array();                                         
    foreach (select_nodes ($dom, '//verify/field') as $field)                                         
    {                                         
        $fields[$field->get_attribute ('name')] = $field->get_content();                                         
    }                                          
    foreach (select_nodes ($dom, '//verify/rooms/recordset/record/field') as $field)                                         
    {                                         
        $arr[] = $field->get_content();                                         
    }                                         
    foreach (select_nodes ($dom, '//verify/dates/recordset/record/field[@name="CustomDate"]') as $field)                                         
    {          
	    $date = $field->get_content();         
	//	if (strtotime($date) > time())                    
            $fields ["CustomDates"][] = $date;                                       
    }                                         
    $fields ["CustomDates"][] = $fields['EventDate'];                                         
    $e_t1 = date('H:i:s',strtotime($fields['EventStartTime']));                                         
    $e_t2 = date('H:i:s',strtotime($fields['EventEndTime']));                                         
    $_GET['cr']='true';                                         
    echo event_range (NULL,NULL,NULL,$arr,NULL,NULL,$e_t1,$e_t2,NULL,'xml',$fields ["CustomDates"]);                                              
}                                         
                                          

function get_properties()                                         
{                                         
    $sql=array('select ep.id, property_name,property_type,property_each,ei.display_text,et.type_name                                         
                from ebp_event_properties ep left outer join ebp_event_property_items ei                                          
                on ei.propertyfk = ep.id inner join ebp_event_property_types                                         
                 et on et.id = ep.property_type');                                         
    return  sql_text($sql, 'xms');                                         
}                                         






function save_property ($dom, $table='ebp_event_properties', $node='property', $key='id')                                         
{                                         
    $fields=array ();                                         
    $i_fields=array ();                                         
    $i_values=array ();                                         
    $u_values=array ();                                         
    $sql = 'update '.$table.' set ';                                         
    foreach (select_nodes ($dom, '//'.$node.'/r/f') as $field)                                         
    {                                         
        $n=$field->get_attribute ('n');                                         
        if ($n==$key) $id=$field->get_content();                                         
        else if ($n=='type_name') { /* do nothing */ }                                          
        else if ($n=='property_item') $item=$field->get_content();                                         
        else                                         
        {                                         
            $fields[$n] = $field->get_content();                                         
            $values[] .= "\n$n='".$fields[$n]."'";                                         
            $i_fields[] .= "".$n."";                                         
            $i_values[] .= "'".$fields[$n]."'";                                         
        }                                         
    }                                          
    if ($id>0)                                             
    {                                         
        $sql = 'update '.$table.' set ' . implode (',', $values) . ' where ' . $key . ' = ' . $id;                                         
        echo $sql . "\n";                                         
        form_database_query($sql) ;                                         
    }                                         
    else                                          
    {                                          
        $sql = 'insert into '.$table.' (' . implode (',', $i_fields) . ') values (' . implode (',', $i_values) . ')';                                         
        echo $sql . "\n";                                         
        form_database_query($sql) ;                                         
        $sql_id_result = form_database_query("SELECT $key FROM $table ORDER BY $key DESC") ;                                         
        if ($row = mysql_fetch_array($sql_id_result, MYSQL_ASSOC))                                          
        {                                         
            $id = $row[$key];                                          
            echo 'id is {'.$id.'}';                                         
        }                                            
    }                                         
                                             
                                             
                                              
                                             
                                             
                                              
    $sql = sql_delete_from ("ebp_event_property_items", "propertyfk", $id);                                          
    echo $sql . "\n";                                         
    form_database_query($sql) ;                                         
                                             
    $item=explode (',',$item);                                         
    for ($i=0;$i<sizeof($item);$i++)                                         
    {                                         
        if (strlen(trim($item[$i])) > 0)                                         
        {                                         
            $sql = 'insert into ebp_event_property_items (display_value,display_text,propertyfk) values ("'.trim($item[$i]).'","'.trim($item[$i]).'",'.$id.')';                                         
            echo $sql . "\n";                                          
            form_database_query($sql) ;                                         
        }                                         
    }                                          
}                                         
                                            

function transform ($dom, $text)                                         
{                                         
    if ($xsl = domxml_xslt_stylesheet ($text))                                                
    {                                               
        if ($result = $xsl->process($dom, $params))                                                
        {                                               
             return $xsl->result_dump_mem($result);                                                  
        }                                              
    }                                          
    return false;                                         
}                                         




$profile_doc = 'xml/profile.xml';                                         
$transform_doc = 'xsl/TMPproflist.xsl';                                         

if ($dom=domxml_open_mem($input))                                                                                                                                
{                                                   
    $config=select_single_node ($dom,'//config');          
    $bulk=select_single_node ($dom,'//bulk.execute');          
    $mail=select_single_node ($dom,'//email');          
    $verify=select_single_node ($dom,'//verify');                                         
    $usernd=select_single_node ($dom,'//user');                                         
    $roomnd=select_single_node ($dom,'//saveroom');                                     
    $calendar=select_single_node ($dom,'//calendar');                                         
    $catnd=select_single_node ($dom,'//category');                                         
    $eventnd=select_single_node ($dom,'//event');                                         
    $propnd=select_single_node ($dom,'//property');                                       
    $report=select_single_node ($dom,'//report');                                         
    $expnd=select_single_node ($dom,'//export/rs');                                         
    $profnd=select_single_node ($dom,'//*[local-name()="profile"]');                                         
    if ($expnd)                                         
    {                                         
        #$s=str_replace ('<export>','',$input);                                         
        $s=str_replace ('</export>', '', str_replace ('<export>','',$input));                                         
        if ($dom=domxml_open_mem($s))                                          
        {                                         
            $fp=fopen ($transform_doc, 'r');                                         
            $fr=fread ($fp,filesize($transform_doc));                                         
            fclose ($fp);                                         
                                                     
                                                     
            $profnd=select_single_node ($dom,'//*[local-name()="profile"]');                                         
            if ($profnd) $profnd->set_attribute ('usepages','false');                                         
                                                     
                                                     
            $op= transform ($dom, str_replace('&#160;',' ',$fr));                                            
            $outdoc = time();                                         
            $fp=fopen ('xml/' . $outdoc, 'w');                                         
            fwrite ($fp,$op);                                         
            fclose ($fp);                                         
            echo $outdoc;                                          
        }                                          
    }                                         
    else if ($config)                                         
    {                   
        set_config ($dom);                                     
    }                                         
    else if ($mail)                                         
    {                                                
        foreach (select_nodes ($dom, '//header') as $field)                                         
        {                                         
            $to         = $field->get_attribute ('to');           
            $from       = $field->get_attribute ('from');          
            $subject    = $field->get_attribute ('subject');                                     
        }                                            
        foreach (select_nodes ($dom, '//body') as $field)                                         
        {                                         
            $body=$field->get_content ();                                     
        }             
                   
           
                 
        $mail_sent = mail($to, $subject, $body, "To: The Receiver <" . $to . ">\n" .           
    "From: The Sender <sender@some.net>\n" .           
    "MIME-Version: 1.0\n" .           
    "Content-type: text/html; charset=iso-8859-1");          
               
        echo $mail_sent ? 'Mail was sent to ' . $to : "Mail failed (" . strlen ($body) . " bytes)";               
                 
                                   
    }                                               
    else if ($bulk)                                         
    {                   
        bulk_execute ($dom);                                     
    }                                         
    else if ($profnd)                                         
    {                                         
        $dom->dump_file($profile_doc, false, true);                                            
        echo 'Profile was saved!';                                                
    }                                         
    else if ($eventnd)                                         
    {  
		$cloneid   = $eventnd->get_attribute ('cloneid'); 
		$clonedate = $eventnd->get_attribute ('clonedate');     
		if (strlen($cloneid) > 0)
		{
			$clonedate = date ('Y-m-d', strtotime($clonedate));
            $sql = "DELETE FROM recursecustom WHERE CustomDate='" . $clonedate . "' and EventFk='" . $cloneid . "'";  echo   "\n$sql\n"; 
			form_database_query ($sql);  
		}                                  
        save_event ($dom);                                                    
    }                                         
    else if ($propnd)                                         
    {                                         
        save_property ($dom);                                                    
    }                                         
    else if ($report)                                         
    {                   
        save_generic ($dom, 'customreports', 'report', 'id');                                                                     
    }                                           
    else if ($calendar)                                         
    {                   
        save_generic ($dom, 'ebp_event_calendars', 'calendar', 'id');                                                                     
    }                                         
    else if ($catnd)                                         
    {                                         
        save_generic ($dom, 'eventfolders', 'category', 'id');                                         
    }                                         
    else if ($roomnd)                                         
    {                                         
        save_generic ($dom, 'rooms', 'saveroom');                                         
    }                                         
    else if ($usernd)                                         
    {                                         
        save_generic ($dom);                                         
    }                                         
    else if ($verify)                                         
    {                                         
        verify_event ($dom);                                         
    }                                         
    else                                         
    {                                         
        save_event ($dom);                                                                                                                                               
        echo 'OK';                                                                         
    }                                         
}                                                 
else if ($action=='read')                                         
{                                         
    header("Pragma: public"); // required                                          
    header("Expires: 0");                                          
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");                                          
    header("Cache-Control: private",false); // required for certain browsers                                           
    header("Content-type: application/vnd.ms-excel");                                           
    header("Content-Disposition: attachment; filename=\"eb" . get('doc') . "." . get('op') . "\";" );                                          
    $indoc = 'xml/' .  get('doc');                                         
    $fp=fopen ($indoc, 'r');                                         
    $fr=fread ($fp,filesize($indoc));                                         
    fclose ($fp);                                         
    echo $fr;                                         
    unlink ($indoc);                                         
}                                                  
else if ($action=='get_config')                                         
{                        
    get_config();                                    
}                                                  
else if ($action=='range')                                         
{                     
	header ('Content-type: text/xml');                    
    echo date_range($id);                                         
}                                               
else if ($action=='profile')                                         
{                                         
    $fp=fopen ($profile_doc, 'r');                                         
    $fr=fread ($fp,filesize($profile_doc));                                         
    fclose ($fp);                                         
    echo $fr;                                         
}                                         
else if ($action=='prop')                                         
{                                         
    echo prop_list($id);                                         
}                                         
else if ($action=='login')                                         
{                                         
    echo sql_text(array("select * from event_users where userid='".get('uid')."' and password='".get('pass')."'"), 'xml');                                         
                                             
                                             
    $temp   = form_database_query("SELECT ID FROM event_users WHERE userid='".get('uid')."' and password='".get('pass')."'");                                         
    while($row = mysql_fetch_array($temp, MYSQL_ASSOC))                                           
    {                                             
        $id=$row["ID"];                                         
                                                 
        $sql = sql_delete_from ("ebp_ip", "ip", $_SERVER['REMOTE_ADDR']);                                          
        form_database_query($sql) ;                                         
        if (isset($_GET['ku']))                                         
        {                                         
            if (get('ku')=='1')                                         
            {                                         
                form_database_query('insert into ebp_ip (ip,userfk,remember) values ("'.$_SERVER['REMOTE_ADDR'].'", '.$id.', '.get('kp').')') ;                                         
            }                                         
        }                                         
    }                                             
                                             
}                                         
else if ($action=='raw')                                         
{                                                            
    $query  = 'select * from events';                                     
    $result = form_database_query($query);                                          
    $max 	=  mysql_num_rows($result) ;
	$start  = get('start', 0);
	if ($start > 0)
	{
	     $ok=mysql_data_seek ($result,$start);
	}
	$i=0;
    while($row =mysql_fetch_assoc($result))                                                                
    {                                              
        $test = form_database_query('select * from  jct_event_calendar where EventFk='.$row['ID']);
		if (mysql_num_rows($test)==0)
		{
			$name=strtolower($row['EventName']);
			if (strpos($name,'test')===false && strpos($name,'milton')===false && strpos($name,'mark')===false && strpos($name,'new event')===false && strpos($name,'do not post')===false)
			{
				echo ("<div style='font:10pt georgia;color:red'>adding " . $row['EventName'] . '</div>');
		        form_database_query("INSERT INTO jct_event_calendar (EventFk,Calendar) VALUES(".$row['ID'].", 4)");    
			}      
		}   
		else echo ("<div style='font:9pt georgia;color:gray'>Found " . $row['EventName'] . '</div>');
		$start ++;        
		$i++;
		if ($i>100) break;                            
    }             
	if ($start < $max)   
	{
	
		echo '<script>location.href="'.$_SERVER['SCRIPT_NAME'].'?action=raw&start='.$start.'"</script>';
	}                             
}                                         
else if ($action=='dump')                                         
{                                         
    $sql='select * from '.$id;                                         
    if ($id=='rooms') $sql = 'select r.*, count(eventfk) as EventCount from rooms r left outer join                                          
                                event_rooms er on r.ID = er.roomfk                                         
                                group by roomname';                                         
    if ($id=='customreports') echo "<!-- utf8_encoded -->\n" .  sql_text(array($sql), '128');        
	else echo sql_text(array($sql), get('op', 'csv'));                         
}                                         
else if ($action=='property')                                         
{                                         
    echo get_properties ();                                         
}                                         
else if ($action=='category')                                         
{                                         
    echo event_category ($id);                                         
}                                         
else if ($action=='event')                                         
{ # event_range ($s1=NULL,$s2=NULL,$next5=NULL,$rm=NULL,$nm=NULL)                                         
    echo event_range (get('s1'),get('s2'),NULL,isset($_GET['rm'])?array(get('rm')):NULL,get('nm'),get('us'),get('t1'),get('t2'),get('da'),get('op', 'csv'));                                         
}                                          
else if ($action=='next5')                                         
{ #  NULL,NULL,NULL,NULL,NULL,-2,get('op', 'csv')                                         
    echo event_range (NULL,NULL,true, NULL,NULL,NULL,NULL,NULL,-2, get('op', 'csv'));                                         
}                                         
else if ($action=='roomlist')                                         
{                                         
    echo event_room_list($id);                                         
}                                       
else if ($action=='roomchange')                                   
{                                   
    form_database_query ( sql_delete_from ("event_rooms", "eventfk", get('id')) );                                   
    $rooms = explode (',',get('rooms'));                                  
    form_database_query ('UPDATE events SET RoomID = ' . $rooms[0] . ' WHERE ID=' . get('id'));                                 
    foreach ($rooms as $room)                                  
    {                                  
        $sql = "INSERT INTO event_rooms (eventfk,roomfk) VALUES (" . get('id') . ", " . $room . ")";                                   
       form_database_query($sql) ;                                   
    }                                  
}                                     
else if ($action=='scope')                                         
{                                         
    echo event_date_scope(strtotime($s1), strtotime($s2), $tp, $ui);                                         
}                                         
else if ($action=='delete_event')                                         
{                                         
    delete_event (get('id'));                                         
}                                         
else if ($action=='delete_user')                                         
{                                         
    delete_user (get('id'));                                         
}                           
else if ($action=='delete_room')                                         
{                                         
	$sql = sql_delete_from ("rooms", "ID", get('id'));                                          
	form_database_query($sql) ;                                         
}                     
else if ($action=='delete_attachment')                    
{                  
     $sql = sql_delete_from ("ebp_event_attachments", "id",  get('id'));                                       
     form_database_query($sql) ;                                          
}          
else if ($action=='delete_calendar')                    
{                  
     $sql = sql_delete_from ("ebp_event_calendars", "id",  get('id'));                                       
     form_database_query($sql) ;                                          
}           
else if ($action=='delete_report')                    
{                  
     $sql = sql_delete_from ("customreports", "id",  get('id'));                                       
     form_database_query($sql) ;                                          
}                     
else if ($action=='sql_calendar')                    
{                  
    echo sql_calendar (get('id'),get('start'),get('end'));                                    
}                     
else if ($action=='sql_featured')                    
{                    
    sql_featured ();     # sql_calendar ($id,$start,$end)               
}                                         
else if ($action=='delete_custom')                                         
{                                         
    $sql = "DELETE FROM recursecustom WHERE CustomDate='" . get('date') . "' and EventFk='" . get('eventfk') . "'";                                          
    echo '{'.get('eventfk').'}';                                      
     form_database_query($sql) ;                                         
}                                           
else if ($action=='reset_event_date')                                         
{                                         
    $sql = "UPDATE events set EventDate='" . get('date') . "' WHERE ID='" . get('id') . "'";                                          
    echo '{'.get('id').'}';                                      
     form_database_query($sql) ;                                         
}                                           
else if ($action=='reset_event_time')                                         
{                                         
    $sql = "UPDATE events set " . get('type','Event') . "" . get('marker') . "Time='" . get('value') . "' WHERE ID='" . get('id') . "'";                                          
    echo '{'.get('id').'}';                                      
     form_database_query($sql) ;                                         
}                                           
else if ($action=='reset_event_times')                                         
{                                         
    $sql = "UPDATE events set EventStartTime='" . str2time( get('es') ) . "',        
                              EventEndTime='" . str2time( get('ee') ) . "',        
                              SetupStartTime='" . str2time( get('ss') ) . "',        
                              SetupEndTime='" . str2time( get('se') ) . "'        
                              WHERE ID='" . get('id') . "'";                                          
    echo '{'.get('id').'}';                                      
    form_database_query($sql) ;                                         
}                                       
else if ($action=='swap_event_date')                                         
{                                         
    $sql = "DELETE FROM recursecustom WHERE CustomDate='" . get('old') . "' and EventFk='" . get('id') . "'";                                          
    form_database_query($sql) ;    echo ($sql);                                     
    $sql = "DELETE FROM recursecustom WHERE CustomDate='" . get('date') . "' and EventFk='" . get('id') . "'";                                          
    form_database_query($sql) ;    echo ($sql);                                     
    $sql = "INSERT INTO recursecustom (CustomDate,EventFk) VALUES ('" . get('date') . "', '" . get('id') . "')";                                          
    form_database_query($sql) ;    echo "\n\n" . $sql;                                            
    echo '{'.get('id').'}';                                   
}                                    
else if ($action=='delete_category')                                         
{                                         
    $sql = sql_delete_from ("eventfolders", "id", get('id'));                                          
     form_database_query($sql) ;                                         
}                                         
else if ($action=='delete_property')                                         
{                                         
    $sql = sql_delete_from ("ebp_event_properties", "id", get('id'));                                          
    echo $sql . "\n";                                         
    form_database_query($sql) ;                                         
    $sql = sql_delete_from ("ebp_event_property_items", "propertyfk", get('id'));                                          
    echo $sql . "\n";                                         
    form_database_query($sql) ;                                         
}                                          
else if ($action=='server')                                         
{                                         
  print_r ($_SERVER);                                         
}                                         
else if ($action=='attach')                                         
{                      
    $sql = 'select id, eventfk, attachment_name, attachment_type, attachment_size from ebp_event_attachments where eventfk=' . get ('id');                                          
    echo sql_text(array($sql), 'xml');                                                            
}                                         
else if ($action=='check')                                         
{                                          
    $sql = "select u.userid,                                         
        ( CASE WHEN e.remember = 0 THEN '' ELSE u.password END ) as password,e.remember                                         
        from event_users u inner join                                         
        ebp_ip e on u.ID = e.userfk                                         
        where e.ip = '".$_SERVER['REMOTE_ADDR']."'";                                         
     echo sql_text(array($sql), 'xml');                                         
}                                         
else if ($action=='log')                                         
{                                          
    $sql = 'select l.id, l.Userfk, DATE_FORMAT(l.DateModified, "%W %b %e, %Y %r") EditDate,                                          
             CONCAT(eu.FirstName," ",eu.LastName) as FullName                                         
            from log l inner join event_users eu on                                         
            l.Userfk = eu.ID                                         
            where l.eventfk = '.get('id').' ';                                         
    echo sql_text(array($sql), 'xml');                                         
}                                         
else if ($action=='comments')                                         
{                                          
    $sql = 'select ec.id, ec.UserID, DATE_FORMAT(ec.CommentDate, "%W %b %e, %Y %r") CommentDate,                                          
            ec.CommentText, ec.EventFK, CONCAT(eu.FirstName," ",eu.LastName) as FullName                                         
            from eventcomments ec inner join event_users eu on                                         
            ec.UserID = eu.ID                                         
            where ec.eventfk = '.get('id').' ';                                         
    echo sql_text(array($sql), 'xml');                                         
}                                         
else if ($action=='conflicts')                                         
{                                          
    $sql = "select CustomDate as EventDate from recursecustom                                          
            where eventfk = ".get('id')."                                         
            union                                          
            select EventDate from events where id = ".get('id')."";                                         
    echo date_range(NULL, $sql); //sql_text(array($sql), 'xml');                                         
}                                         
else if ($action=='eventroomlist')                                         
{                                          
    $sql = 'select er.eventfk, er.roomfk, r.RoomName from event_rooms er inner join rooms r on                                         
            r.ID=er.roomfk where eventfk in ('.get('id').') order by er.eventfk';                                         
    echo sql_text(array($sql), 'xml');                                         
}                                         
else if ($action=='feature')                                         
{                                          
    $sql = 'update events set Featured = ' . get('value') . ' where id = ' . get('id') . ' ';                                         
    form_database_query($sql);                                         
}                                         
else if ($action=='userperm')                                         
{                                          
    $sql = 'update event_users set Mask = ' . get('mask') . ' where id = ' . get('id') . ' ';                                         
    form_database_query($sql);                                         
}                                         
else if ($action=='calendar')                                         
{                                          
    $sql = 'select j.* from jct_event_calendar j
	        inner join ebp_event_calendars e on e.id = j.Calendar where j.eventfk in (' . get('id') . ')  ';                                         
    echo sql_text(array($sql), 'xml');                                         
}                                         
else if ($action=='backup')                                         
{                                          
    echo backup_db (get('id'), get('key'), get('start'));                                         
}                                         
else if ($action=='metrics')                                         
{                                          
    $sql = 'select "/webservices/images/explorer/Calendar_sm2.gif" as icon, "eventcount" as name, count(id) as num from events union                                          
            select "/webservices/images/explorer/ico_avatar.gif" as icon, "usercount" as name, count(id) as num from event_users union                                          
            select "/webservices/images/xui.graph.gif" as icon, "roomcount" as name, count(id) as num from rooms union                                          
            select "/webservices/images/i.s.property.gif" as icon, "propcount" as name, 0 as num';                                         
    echo sql_text(array($sql), 'xms');                                                 
}                                         
else if ($action=='dump_recurse')                                         
{                  
	dump_recurse();                                                                  
}                                         
else if ($action=='remind')                                         
{                                          
    $sql = "select u.userid,u.password                                          
            from event_users u                                         
            where EMail = '".get('e')."'";                                         
     $temp = form_database_query($sql);                                         
    if ($row = mysql_fetch_array($temp, MYSQL_ASSOC))                                           
    {                                             
        $userid=$row["userid"];                                         
        $password=$row["password"];                                          
        mail(get('e'), 'Password reminder', 'EventBuilder User ID: '.$userid.', Password: ' . $password);                                             
        echo 'Your password has been mailed to ' . get('e');                                         
        exit;                                         
    }                                             
    echo 'Your password could not be found!';                                         
}                                         
else          
{         
    echo 'No valid xml or query string was received';         
    print_r ($_GET);                                         
}         

function str2time ($x) { return date ('H:i:s', strtotime($x)); }       

function get ($n,$v=NULL)                                         
{                                         
    return isset($_GET[$n]) ? $_GET[$n] : $v;                                         
}                                         

function text128 ($text)
{
    $o=array();
	for ($i=0;$i<strlen($text);$i++)
	{
	    $c=substr($text,$i,1);
		$o[]=$c;
	} 
	return implode ('', $o);
}


/*                                         

            $special = array ();                                         
            $output .= sql_text ($special, $type, true, NULL, 0, NULL, NULL, 'calendars');                                            
*/                                         
?>